const express = require("express");
const router = express.Router();
const bodyParser = require("body-parser");
const bcrypt = require("bcrypt");
const user = require("../models/users.js");
const multer = require("multer");
const fs = require("fs");
const path = require("path");
const session = require("express-session")

router.use(bodyParser.urlencoded({ extended: false }))
let file = multer({ dest: "./upload" });

router.use(session({
    secret: 'secret', // 对session id 相关的cookie 进行签名
    resave: true,
    saveUninitialized: false, // 是否保存未初始化的会话
    cookie: {
        maxAge: 1000 * 3600 * 60, // 设置 session 的有效时间，单位毫秒
    },
}));

router.post("/register", async(req, res) => {

    let findResult = await user.findOne({ email: req.body.email })

    if (findResult) {
        return res.send({ code: 1, success: false, data: "该邮箱已被注册" })
    } else {
        bcrypt.genSalt(10, function(err, salt) {
            bcrypt.hash(req.body.password, salt, (err, hash) => {
                if (err) {
                    return err;
                }
                user.create({ name: req.body.name, password: hash, email: req.body.email, imgPath: req.body.imgPath }, (err, docs) => {
                    if (docs) {
                        req.session.status = 1;
                        // req.session.userId = docs._id;
                        res.send({ code: 0, success: true })
                    }
                })
            });
        });
    }
})

router.get("/register", (req, res) => {
    if (req.session.status) {
        res.redirect("/login")
    }
    res.render("register", {
        path: "demo1"
    })
})

router.post("/upload", file.single('pic'), (req, res) => {
    let filename = req.file.filename;
    let extname = path.extname(req.file.originalname);
    let newPath = `/${filename}${extname}`;
    fs.rename(`./upload/${filename}`, `./upload/${filename}${extname}`, (err, data) => {
        if (err) {
            return res.json("请求失败")
        }
        let obj = JSON.stringify({ code: 0, path: newPath })
        res.send(obj)
    })

})

router.get("/login", (req, res) => {

    res.render("login", {
        path: "login"
    })
})

router.post("/login", async(req, res) => {
    let findResult = await user.findOne({ name: req.body.name });
    if (!findResult) {
        return res.json({ code: 1, success: false, data: "改用户不存在，请重新输入" })
    }
    let isMatch = await bcrypt.compare(req.body.password, findResult.password);
    if (isMatch) {
        req.session.status = 1;
        return res.json({ code: 1, success: true, data: "登陆成功" })
    } else {
        return res.json({ code: 1, success: false, data: "密码错误" })
    }
})

router.get("/", (req, res) => {
    if (!req.session.status) {
        res.redirect("/login")
    } else {
        res.render("home")
    }

})


module.exports = router;